import numpy
from general_neuro.fast_thresh_detect import fast_thresh_detect

def read_wessel_text_file(filename, time_column=-1, data_column=0, 
                                    pulse_column=2, time_unit = 0.001):
    """
    read_file returns 1) a list of voltage traces and 
                      2) a sampling rate in Hz.
                      3) pulse onset index

    """

    data = numpy.loadtxt(filename)
    voltage_traces = data.T[data_column]
    times = data.T[time_column]
    pulse_trace = data.T[pulse_column]
    sample_rate = int(len(times)/(times[-1]*time_unit))
    pulse_trace_threshold_crossings = fast_thresh_detect(pulse_trace, 
                                      threshold=numpy.average(pulse_trace))
    # check for a pulse who's onset wasn't recorded.
    threshold_crossing = pulse_trace_threshold_crossings[0]
    if pulse_trace[threshold_crossing] > pulse_trace[threshold_crossing+1]:
        print "WARNING: Found only negative going threshold crossing... Assuming pulse onset at index 0!!!!"
    pulse_index = pulse_trace_threshold_crossings[0]

    return voltage_traces, sample_rate, pulse_index
